package cmbchina.util.http;


import cmbchina.util.AjaxJson;
import cmbchina.util.AppConfig;
import cmbchina.util.JacksonUitl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
 *
 * 调用itil工具类
 */
public class DbServiceRequestUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(DbServiceRequestUtil.class);
    public static Properties appConfig = AppConfig.getInstance().getConfig();
    private static  String dashboard_url= appConfig.getProperty("db.service.url");
    private static String dashboard_usernmae = "" ;
    private static String dashboard_passWorld = "";
    private static int dashboard_port = Integer.parseInt(appConfig.getProperty("db.service.port"));
    private static String dashboard_protocol = "http";
//    private static String dashboard_apiurl ="/ngap/api/operation/rs6000/exec_command";
/*
    private static  String dashboard_url= "99.1.76.195";
    private static String dashboard_usernmae =  "sjkjkpt";
    private static String dashboard_passWorld = "sjkjkpt@123456";
    private static int dashboard_port = 80;
    private static String dashboard_protocol = "http";
    private static String dashboard_apiurl = "/ngap/api/operation/rs6000/exec_command";*/

    /**
     * rest post 方式调用itil接口
     * @param JsonParams json格式的请求参数
     * @return
     * @throws Exception
     */
    public  AjaxJson httpRequestPost(String JsonParams,String dashboard_apiurl){

        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(false);
        ajaxJson.setMsg("AIX");
        try{

        HttpHost targetHost = new HttpHost(dashboard_url, dashboard_port, dashboard_protocol);

        DefaultHttpClient httpclient = new DefaultHttpClient();
       /* 请求超时*/
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*60*60);
        /*读取超时*/
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000*60*60);

        //此用户名和密码上生产前需要修改为自己的账户
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(dashboard_usernmae, dashboard_passWorld));

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        String url = dashboard_protocol+"://"+dashboard_url+":"+dashboard_port+dashboard_apiurl;

        HttpPost httpPost = new  HttpPost(url);

        StringEntity stringEntity = new StringEntity(JsonParams, HTTP.UTF_8);

        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("accept","application/json");

        httpPost.setEntity(stringEntity);

        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);

        HttpEntity entity = response.getEntity();

        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(dashboard_apiurl+" ====================StatusCode:" + statusCode);
        Map<String,Object> mapResult = new HashMap<String,Object>();

        if(statusCode == 200) {

            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));
            String buffer  = "";
            StringBuffer sb = new StringBuffer();
            while((buffer = reader.readLine())!=null){
                sb.append(buffer);
            }
            reader.close();
            httpPost.releaseConnection();
            System.out.println("entity:" + sb.toString());
            httpclient.getConnectionManager().shutdown();


            ajaxJson = JacksonUitl.getObjectMapper().readValue(sb.toString(), AjaxJson.class);

        }else{
            ajaxJson.setCode(statusCode+"");
            ajaxJson.setMsg(statusCode+"");


        }

        }catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setCode("400");
            LOGGER.error("",e);
        }

        return ajaxJson;
    }

    public AjaxJson CheckScriptNameRequest(String requestParams){

        String apiUrl = "/api/rest/queryScriptType";
        return this.httpRequestPost(requestParams,apiUrl);
    }

    public AjaxJson sendSms(String requestParams){

        String apiUrl = "/api/rest/sendMsm";
        return this.httpRequestPost(requestParams,apiUrl);
    }

    public AjaxJson queryOperPhone(String requestParams){

        String apiUrl = "/api/rest/queryOperPhone";
        return this.httpRequestPost(requestParams,apiUrl);
    }

    public AjaxJson checkItilNum(String requestParams){
        String apiUrl = "/api/rest/checkItilNumber";
        return this.httpRequestPost(requestParams,apiUrl);
    }



//    public static void main(String[] args) throws Exception {
//
//        String pp = "{\"shellName\":\"ls \", \"shellParam\":\"\", \"hostNames\":\"\", \"userName\":\"\"}";
////        Map<String,Object> mapResult = DbServiceRequestUtil.httpRequestPost(pp);
//        System.out.println("Hello World");
//        String sb = "{\"success\":\"true\", \"msg\":\"test\"}";
//        AjaxJson ajaxJson=JacksonUitl.getObjectMapper().readValue(sb.toString(), AjaxJson.class);
//
////        int i = 0;
//
////        String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
////        char[] rands = new char[6];
////        for (int i = 0; i < rands.length; i++)
////        {
////            int rand = (int) (Math.random() * a.length());
////            rands[i] = a.charAt(rand);
////        }
////        for(int i=0;i<rands.length;i++){
////            System.out.println(rands[i]);
////        }
//    }




}
